<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/14/0014
 * Time: 11:12
 */

namespace app\sports_admin\model;


use think\Db;
use think\Model;

class Course extends Model
{
    protected $table = 'course';

    protected $pk = 'id';

    protected $autoWriteTimestamp = true;

    public function getTeacherInfo()
    {
        return $this->belongsTo('teacher','teacher_id','id')->field('id,school_id,teacher_name');
    }
    /**
     * 获取排课信息
     * @param $page 第几页
     * @param $rows 每页显示的条数
     * @param $sort 要排序的字段
     * @param $sortOrder 升序/降序
     * @param $courseName 课程名称
     * @param $teacherName 教师名称
     * @param $schoolName 学校名称
     * @param $year 要检索的学年
     */
    public static function getCourseInfo($page,$rows,$sort,$sortOrder,$courseName,$teacherName,$schoolName,$year)
    {
        $result = self::with(['getTeacherInfo'=>function ($query) use ($teacherName,$schoolName){
                if($teacherName){
                    $query->where('teacher_name','like',"%{$teacherName}%");
                }
                $query->with(['school'=>function($querys)use($schoolName){
                    if($schoolName){
                        $querys->where('school_name','like',"%{$schoolName}%");
                    }
                }]);
            }])->where(function($query) use ($courseName,$year){
                if($courseName){
                    $query->where('course_name','like',"%{$courseName}%");
                }
                if($year){
                    $query->where('year',$year);
                }
            })->order("{$sort}","{$sortOrder}")->limit($rows)->page($page)->select();
        $count = self::with(['getTeacherInfo'=>function ($query) use ($teacherName,$schoolName){
                if($teacherName){
                    $query->where('teacher_name','like',"%{$teacherName}%");
                }
                $query->with(['school'=>function($querys)use($schoolName){
                    if($schoolName){
                        $querys->where('school_name','like',"%{$schoolName}%");
                    }
                }]);
            }])->where(function($query) use ($courseName,$year){
                if($courseName){
                    $query->where('course_name','like',"%{$courseName}%");
                }
                 if($year){
                    $query->where('year',$year);
                }
            })->count();
        return ['total'=>$count,'rows'=>$result];
    }
}